#include "linklist.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct _TagLinklist
{
        LinkListNode header;
        int length;
}TLinklist;


LinkList* LinkList_Create()
{
        TLinklist *tmp = NULL;
        
        tmp = (TLinklist *)malloc(sizeof(TLinklist));
        if(tmp == NULL){
                return tmp;       
        }
        memset(tmp, 0, sizeof(TLinklist));
        tmp->length = 0;
        tmp->header.next = NULL;

        return tmp;
}

void LinkList_Destory(LinkList* list)
{
        if(list != NULL){
                free(list);
                list = NULL;
        }
        return ;
}

//让链表恢复到初始化状态
void LinkList_Clear(LinkList* list)
{
        TLinklist *tmp = NULL;
        if(list == NULL){
                return ;
        }
        tmp = (TLinklist *)list;

        tmp->length = 0;
        tmp->header.next  = NULL;

        return ;
}

int LinkList_Length(LinkList* list)
{
        TLinklist *tmp = NULL;
        if(list == NULL){
                return -1;
        }
        tmp = (TLinklist *)list;
        return tmp->length;
}

//指针指向谁就把谁的地址给指针
//分清楚 链表的操作逻辑 和 辅助指针变量之间的关系
int LinkList_Insert(LinkList* list, LinkListNode* node, int pos)
{
        int i = 0;
        TLinklist *tmp = NULL;
        LinkListNode *current = NULL;

        if(list == NULL || node == NULL || pos < 0){ 
                return -1;
        }
        tmp = (TLinklist *)list;
        current = &(tmp->header);
        
        for (i = 0; i < pos  && (current->next != NULL); i++)
        {
                current = current->next;
        }
        
        //1.让新插入node连接后续链表
        node->next = current->next;
        //2. 让前面的链表 连接新的node节点
        current->next = node;
        tmp->length++;

        return 0;
}

LinkListNode* LinkList_Get(LinkList* list, int pos)
{
        int i = 0;
        TLinklist *tmp = NULL;
        LinkListNode *current = NULL;

        if(list == NULL || pos < 0){ 
                return NULL;
        }

        tmp = (TLinklist *)list;
        current = &(tmp->header); //让辅助指针变量指向链表的头部
        
        for (i = 0; i < pos  && (current->next != NULL); i++) //跳pos次
        {
                current = current->next;
        }
        return current->next;
}

LinkListNode* LinkList_Delete(LinkList* list, int pos)
{
        int i = 0;
        TLinklist *tmp = NULL;
        LinkListNode *current = NULL;
        LinkListNode *ret = NULL;

        if(list == NULL || pos < 0){ 
                return NULL;
        }
        tmp = (TLinklist *)list;
        current = &(tmp->header);
        
        for (i = 0; i < pos  && (current->next != NULL); i++)
        {
                current = current->next;
        }

        //缓存被删除的节点的位置
        ret = current->next;
        //连线
        current->next = ret->next;
        tmp->length--;
        
        return ret;
}